<template>
  <div class="add-todo">
    <h2>添加新任务</h2>
    <form @submit.prevent="handleSubmit" @keydown.ctrl.enter="handleSubmit">
      <div class="form-group">
        <label for="title">标题 *</label>
        <input 
          type="text" 
          id="title" 
          v-model="form.title" 
          required
          placeholder="请输入任务标题"
          @keydown.esc="resetForm"
        >
      </div>
      
      <div class="form-group">
        <label for="description">描述</label>
        <textarea 
          id="description" 
          v-model="form.description"
          placeholder="请输入任务描述（可选）"
        ></textarea>
      </div>
      
      <div class="form-group">
        <label for="due-date">截止时间</label>
        <input 
          type="datetime-local" 
          id="due-date" 
          v-model="form.dueDate"
        >
      </div>
      
      <div class="form-group">
        <label for="priority">优先级</label>
        <select id="priority" v-model="form.priority">
          <option value="low">低</option>
          <option value="medium" selected>中</option>
          <option value="high">高</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="category">分类</label>
        <select id="category" v-model="form.category">
          <option value="work">工作</option>
          <option value="study">学习</option>
          <option value="life">生活</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="tags">标签</label>
        <input 
          type="text" 
          id="tags" 
          v-model="tagsInput"
          placeholder="用逗号分隔多个标签，如：重要,紧急"
        >
      </div>
      
      <div class="form-group">
        <label for="reminder-time">提醒时间</label>
        <input 
          type="datetime-local" 
          id="reminder-time" 
          v-model="form.reminderTime"
        >
        <small>设置任务提醒时间（可选）</small>
      </div>
      
      <div class="form-group">
        <label class="checkbox-label">
          <input 
            type="checkbox" 
            id="repeat" 
            v-model="form.repeat"
          > 重复任务
        </label>
        <select 
          id="repeat-rule" 
          v-model="form.repeatRule" 
          :disabled="!form.repeat"
        >
          <option value="daily">每日</option>
          <option value="weekly">每周</option>
          <option value="monthly">每月</option>
          <option value="yearly">每年</option>
        </select>
      </div>
      
      <button type="submit">添加任务</button>
      <button type="button" @click="resetForm" class="btn-reset">重置</button>
    </form>
  </div>
</template>

<script>
export default {
  name: 'AddTodoForm',
  data() {
    return {
      form: {
        title: '',
        description: '',
        dueDate: '',
        reminderTime: '',
        priority: 'medium',
        category: 'work',
        repeat: false,
        repeatRule: 'daily'
      },
      tagsInput: '',
      autoSaveTimer: null
    }
  },
  mounted() {
    // 添加快捷键提示
    console.log('提示：按 Ctrl+Enter 可快速提交表单，按 ESC 可清空表单');
    
    // 从本地存储中恢复自动保存的数据
    this.loadAutoSavedData();
  },
  watch: {
    form: {
      handler() {
        this.autoSave();
      },
      deep: true
    },
    tagsInput: {
      handler() {
        this.autoSave();
      }
    }
  },
  methods: {
    autoSave() {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
      }
      
      // 设置新的定时器，1秒后保存
      this.autoSaveTimer = setTimeout(() => {
        const autoSaveData = {
          form: this.form,
          tagsInput: this.tagsInput
        };
        localStorage.setItem('addTodoAutoSave', JSON.stringify(autoSaveData));
        console.log('表单数据已自动保存');
      }, 1000);
    },
    loadAutoSavedData() {
      const savedData = localStorage.getItem('addTodoAutoSave');
      if (savedData) {
        try {
          const data = JSON.parse(savedData);
          this.form = data.form;
          this.tagsInput = data.tagsInput;
          console.log('已恢复自动保存的数据');
        } catch (e) {
          console.error('解析自动保存数据失败:', e);
        }
      }
    },
    handleSubmit() {
      // 处理标签输入
      const tags = this.tagsInput
        .split(',')
        .map(tag => tag.trim())
        .filter(tag => tag);
      
      // 创建待办事项对象
      const newTodo = {
        id: Date.now(), // 简单的ID生成方式
        title: this.form.title,
        description: this.form.description,
        dueDate: this.form.dueDate,
        reminderTime: this.form.reminderTime,
        priority: this.form.priority,
        category: this.form.category,
        tags: tags,
        completed: false,
        repeatRule: this.form.repeat ? this.form.repeatRule : 'none',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      
      // 发送事件到父组件
      this.$emit('add-todo', newTodo);
      
      // 重置表单
      this.resetForm();
    },
    resetForm() {
      this.form = {
        title: '',
        description: '',
        dueDate: '',
        reminderTime: '',
        priority: 'medium',
        category: 'work',
        repeat: false,
        repeatRule: 'daily'
      };
      this.tagsInput = '';
      
      // 清除自动保存的数据
      localStorage.removeItem('addTodoAutoSave');
      
      // 清除自动保存定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
        this.autoSaveTimer = null;
      }
    }
  }
}
</script>

<style scoped>
.add-todo {
  background-color: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

h2 {
  color: #34495e;
  margin-bottom: 15px;
  font-size: 1.5rem;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #2c3e50;
}

.checkbox-label {
  font-weight: normal;
  display: inline-flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  margin-right: 8px;
  width: auto;
}

input, select, textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
}

textarea {
  min-height: 100px;
  resize: vertical;
}

button {
  background-color: #3498db;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
  margin-right: 10px;
}

button:hover {
  background-color: #2980b9;
}

.btn-reset {
  background-color: #95a5a6;
}

.btn-reset:hover {
  background-color: #7f8c8d;
}

@media (max-width: 768px) {
  .add-todo {
    padding: 15px;
  }
  
  button {
    margin-right: 5px;
    margin-bottom: 10px;
    width: auto;
  }
  
  .btn-reset {
    margin-right: 0;
  }
}

@media (max-width: 480px) {
  input, select, textarea {
    padding: 8px;
    font-size: 16px; /* 防止iOS缩放 */
  }
  
  button {
    padding: 10px 15px;
    font-size: 0.9rem;
  }
}
/* 夜间模式样式 */
.dark-mode .add-todo {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

.dark-mode label {
  color: #e0e0e0;
}

.dark-mode input,
.dark-mode select,
.dark-mode textarea {
  background-color: #424242;
  color: #e0e0e0;
  border-color: #555;
}

.dark-mode input:focus,
.dark-mode select:focus,
.dark-mode textarea:focus {
  border-color: #1976d2;
  box-shadow: 0 0 5px rgba(25, 118, 210, 0.3);
}

.dark-mode button {
  background-color: #1976d2;
}

.dark-mode button:hover {
  background-color: #1565c0;
}

.dark-mode .btn-reset {
  background-color: #616161;
}

.dark-mode .btn-reset:hover {
  background-color: #424242;
}

</style>